{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_3dafypt",
    "id": "8C5B8FD488F74207A409DC379EAAFD63",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 卷积神经网络基础\n",
    "\n",
    "本节我们介绍卷积神经网络的基础概念，主要是卷积层和池化层，并解释填充、步幅、输入通道和输出通道的含义。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_hm819qn",
    "id": "254FA5A2E556460089490994E31604D0",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 二维卷积层\n",
    "\n",
    "本节介绍的是最常见的二维卷积层，常用于处理图像数据。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_1w29iz7",
    "id": "839259A7CAD349A7B2CE930E14F9E7B5",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 二维互相关运算\n",
    "\n",
    "二维互相关（cross-correlation）运算的输入是一个二维输入数组和一个二维核（kernel）数组，输出也是一个二维数组，其中核数组通常称为卷积核或过滤器（filter）。卷积核的尺寸通常小于输入数组，卷积核在输入数组上滑动，在每个位置上，卷积核与该位置处的输入子数组按元素相乘并求和，得到输出数组中相应位置的元素。图1展示了一个互相关运算的例子，阴影部分分别是输入的第一个计算区域、核数组以及对应的输出。\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5nfdbhcw5.png?imageView2/0/w/640/h/640)\n",
    "图1 二维互相关运算\n",
    "\n",
    "下面我们用`corr2d`函数实现二维互相关运算，它接受输入数组`X`与核数组`K`，并输出数组`Y`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "graffitiCellId": "id_nculyfq",
    "id": "27AD46C637CE4BF88964BE3C22E6D4DB",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import torch \n",
    "import torch.nn as nn\n",
    "\n",
    "def corr2d(X, K):\n",
    "    H, W = X.shape\n",
    "    h, w = K.shape\n",
    "    Y = torch.zeros(H - h + 1, W - w + 1)\n",
    "    for i in range(Y.shape[0]):\n",
    "        for j in range(Y.shape[1]):\n",
    "            Y[i, j] = (X[i: i + h, j: j + w] * K).sum()\n",
    "    return Y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_nochl8t",
    "id": "12E4EDD4780B4ED3BF46FC98E0671987",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "构造上图中的输入数组`X`、核数组`K`来验证二维互相关运算的输出。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "graffitiCellId": "id_ou9gykf",
    "id": "D6B5388CE30B4280A8EAC9C1E6160CED",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[19., 25.],\n",
      "        [37., 43.]])\n"
     ]
    }
   ],
   "source": [
    "X = torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])\n",
    "K = torch.tensor([[0, 1], [2, 3]])\n",
    "Y = corr2d(X, K)\n",
    "print(Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_kyrga1i",
    "id": "A667995033B54B998459E0CC127B6D96",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 二维卷积层\n",
    "\n",
    "二维卷积层将输入和卷积核做互相关运算，并加上一个标量偏置来得到输出。卷积层的模型参数包括卷积核和标量偏置。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "graffitiCellId": "id_wqfawao",
    "id": "02665E066AC949A2985642A92FC6352A",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "class Conv2D(nn.Module):\n",
    "    def __init__(self, kernel_size):\n",
    "        super(Conv2D, self).__init__()\n",
    "        self.weight = nn.Parameter(torch.randn(kernel_size))\n",
    "        self.bias = nn.Parameter(torch.randn(1))\n",
    "\n",
    "    def forward(self, x):\n",
    "        return corr2d(x, self.weight) + self.bias"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_ywvx25d",
    "id": "C8662D63813F4E5DA12ABFE199E36F24",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "下面我们看一个例子，我们构造一张$6 \\times 8$的图像，中间4列为黑（0），其余为白（1），希望检测到颜色边缘。我们的标签是一个$6 \\times 7$的二维数组，第2列是1（从1到0的边缘），第6列是-1（从0到1的边缘）。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "graffitiCellId": "id_w4j38om",
    "id": "F7CC03E43D714175ADD7D490EE3BC0CB",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 1., 0., 0., 0., 0., 1., 1.],\n",
      "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
      "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
      "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
      "        [1., 1., 0., 0., 0., 0., 1., 1.],\n",
      "        [1., 1., 0., 0., 0., 0., 1., 1.]])\n",
      "tensor([[ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
      "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
      "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
      "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
      "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.],\n",
      "        [ 0.,  1.,  0.,  0.,  0., -1.,  0.]])\n"
     ]
    }
   ],
   "source": [
    "X = torch.ones(6, 8)\n",
    "Y = torch.zeros(6, 7)\n",
    "X[:, 2: 6] = 0\n",
    "Y[:, 1] = 1\n",
    "Y[:, 5] = -1\n",
    "print(X)\n",
    "print(Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_re55xx5",
    "id": "03689A0772F94ABBBE066101211F6299",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "我们希望学习一个$1 \\times 2$卷积层，通过卷积层来检测颜色边缘。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "graffitiCellId": "id_d05ejpd",
    "id": "1D790E2D3B7E4835994C7198A830DA9D",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 5, loss 8.732\n",
      "Step 10, loss 1.441\n",
      "Step 15, loss 0.291\n",
      "Step 20, loss 0.069\n",
      "Step 25, loss 0.018\n",
      "Step 30, loss 0.005\n",
      "tensor([[ 0.9812, -0.9840]])\n",
      "tensor([0.0016])\n"
     ]
    }
   ],
   "source": [
    "conv2d = Conv2D(kernel_size=(1, 2))\n",
    "step = 30\n",
    "lr = 0.01\n",
    "for i in range(step):\n",
    "    Y_hat = conv2d(X)\n",
    "    l = ((Y_hat - Y) ** 2).sum()\n",
    "    l.backward()\n",
    "    # 梯度下降\n",
    "    conv2d.weight.data -= lr * conv2d.weight.grad\n",
    "    conv2d.bias.data -= lr * conv2d.bias.grad\n",
    "    \n",
    "    # 梯度清零\n",
    "    conv2d.weight.grad.zero_()\n",
    "    conv2d.bias.grad.zero_()\n",
    "    if (i + 1) % 5 == 0:\n",
    "        print('Step %d, loss %.3f' % (i + 1, l.item()))\n",
    "        \n",
    "print(conv2d.weight.data)\n",
    "print(conv2d.bias.data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_oytmkp4",
    "id": "6D2014DD040C4AE8928E8D2E8B0E2B27",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 互相关运算与卷积运算\n",
    "\n",
    "卷积层得名于卷积运算，但卷积层中用到的并非卷积运算而是互相关运算。我们将核数组上下翻转、左右翻转，再与输入数组做互相关运算，这一过程就是卷积运算。由于卷积层的核数组是可学习的，所以使用互相关运算与使用卷积运算并无本质区别。所以机器学习中使用的方法属于cross-correlation，而不是卷积，只不过一般称为卷积。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_iv5rdyk",
    "id": "232D9ADECF97429A802C60C0000EF53B",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 特征图与感受野\n",
    "\n",
    "二维卷积层输出的二维数组可以看作是输入在空间维度（宽和高）上某一级的表征，也叫特征图（feature map）。影响元素$x$的前向计算的所有可能输入区域（可能大于输入的实际尺寸）叫做$x$的感受野（receptive field）。\n",
    "\n",
    "以图1为例，输入中阴影部分的四个元素是输出中阴影部分元素的感受野。我们将图中形状为$2 \\times 2$的输出记为$Y$，将$Y$与另一个形状为$2 \\times 2$的核数组做互相关运算，输出单个元素$z$。那么，$z$在$Y$上的感受野包括$Y$的全部四个元素，在输入上的感受野包括其中全部9个元素。可见，我们可以通过更深的卷积神经网络使特征图中单个元素的感受野变得更加广阔，从而捕捉输入上更大尺寸的特征。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_adfhv52",
    "id": "A4CE7D97E9744A138790A9700063083C",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 填充和步幅\n",
    "\n",
    "我们介绍卷积层的两个超参数，即填充和步幅，它们可以对给定形状的输入和卷积核改变输出形状。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_oquq26z",
    "id": "6199F060EBF74BB9894EEDE4F3F845B5",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 填充\n",
    "\n",
    "填充（padding）是指在输入高和宽的两侧填充元素（通常是0元素），图2里我们在原输入高和宽的两侧分别添加了值为0的元素。\n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5nfl6ejy4.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "图2 在输入的高和宽两侧分别填充了0元素的二维互相关计算\n",
    "\n",
    "如果原输入的高和宽是$n_h$和$n_w$，卷积核的高和宽是$k_h$和$k_w$，在高的两侧一共填充$p_h$行，在宽的两侧一共填充$p_w$列，则输出形状为：\n",
    "\n",
    "\n",
    "$$\n",
    "\n",
    "(n_h+p_h-k_h+1)\\times(n_w+p_w-k_w+1)\n",
    "\n",
    "$$\n",
    "\n",
    "\n",
    "我们在卷积神经网络中使用奇数高宽的核，比如$3 \\times 3$，$5 \\times 5$的卷积核，对于高度（或宽度）为大小为$2 k + 1$的核，令步幅为1，在高（或宽）两侧选择大小为$k$的填充，便可保持输入与输出尺寸相同。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_co3p9ym",
    "id": "C31F0DD02A144FC29F738F6A1389E372",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 步幅\n",
    "\n",
    "在互相关运算中，卷积核在输入数组上滑动，每次滑动的行数与列数即是步幅（stride）。此前我们使用的步幅都是1，图3展示了在高上步幅为3、在宽上步幅为2的二维互相关运算。\n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5nflohnqg.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "图3 高和宽上步幅分别为3和2的二维互相关运算\n",
    "\n",
    "一般来说，当高上步幅为$s_h$，宽上步幅为$s_w$时，输出形状为：\n",
    "\n",
    "\n",
    "$$\n",
    "\n",
    "\\lfloor(n_h+p_h-k_h+s_h)/s_h\\rfloor \\times \\lfloor(n_w+p_w-k_w+s_w)/s_w\\rfloor\n",
    "\n",
    "$$\n",
    "\n",
    "\n",
    "如果$p_h=k_h-1$，$p_w=k_w-1$，那么输出形状将简化为$\\lfloor(n_h+s_h-1)/s_h\\rfloor \\times \\lfloor(n_w+s_w-1)/s_w\\rfloor$。更进一步，如果输入的高和宽能分别被高和宽上的步幅整除，那么输出形状将是$(n_h / s_h) \\times (n_w/s_w)$。\n",
    "\n",
    "当$p_h = p_w = p$时，我们称填充为$p$；当$s_h = s_w = s$时，我们称步幅为$s$。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_1idmra0",
    "id": "D6F0F17D97B54D4E843A8792A8B2D568",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 多输入通道和多输出通道\n",
    "\n",
    "之前的输入和输出都是二维数组，但真实数据的维度经常更高。例如，彩色图像在高和宽2个维度外还有RGB（红、绿、蓝）3个颜色通道。假设彩色图像的高和宽分别是$h$和$w$（像素），那么它可以表示为一个$3 \\times h \\times w$的多维数组，我们将大小为3的这一维称为通道（channel）维。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_n6snjjh",
    "id": "9D38698675574834BCF819E18FAA6F21",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 多输入通道\n",
    "\n",
    "卷积层的输入可以包含多个通道，图4展示了一个含2个输入通道的二维互相关计算的例子。\n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5nfmdnwbq.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "图4 含2个输入通道的互相关计算\n",
    "\n",
    "假设输入数据的通道数为$c_i$，卷积核形状为$k_h\\times k_w$，我们为每个输入通道各分配一个形状为$k_h\\times k_w$的核数组，将$c_i$个互相关运算的二维输出按通道相加，得到一个二维数组作为输出。我们把$c_i$个核数组在通道维上连结，即得到一个形状为$c_i\\times k_h\\times k_w$的卷积核。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_xpcj8zq",
    "id": "B43CBA5D4D854AB68291F5D7CB1B5FA5",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 多输出通道\n",
    "\n",
    "卷积层的输出也可以包含多个通道，设卷积核输入通道数和输出通道数分别为$c_i$和$c_o$，高和宽分别为$k_h$和$k_w$。如果希望得到含多个通道的输出，我们可以为每个输出通道分别创建形状为$c_i\\times k_h\\times k_w$的核数组，将它们在输出通道维上连结，卷积核的形状即$c_o\\times c_i\\times k_h\\times k_w$。\n",
    "\n",
    "对于输出通道的卷积核，我们提供这样一种理解，一个$c_i \\times k_h \\times k_w$的核数组可以提取某种局部特征，但是输入可能具有相当丰富的特征，我们需要有多个这样的$c_i \\times k_h \\times k_w$的核数组，不同的核数组提取的是不同的特征。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_t861gfe",
    "id": "2EDA6611AFD148D291D2B9E7AB8C1B50",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 1x1卷积层\n",
    "\n",
    "最后讨论形状为$1 \\times 1$的卷积核，我们通常称这样的卷积运算为$1 \\times 1$卷积，称包含这种卷积核的卷积层为$1 \\times 1$卷积层。图5展示了使用输入通道数为3、输出通道数为2的$1\\times 1$卷积核的互相关计算。\n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5nfmq980r.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "图5 1x1卷积核的互相关计算。输入和输出具有相同的高和宽\n",
    "\n",
    "$1 \\times 1$卷积核可在不改变高宽的情况下，调整通道数。$1 \\times 1$卷积核不识别高和宽维度上相邻元素构成的模式，其主要计算发生在通道维上。假设我们将通道维当作特征维，将高和宽维度上的元素当成数据样本，那么$1\\times 1$卷积层的作用与全连接层等价。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_6hb1wnk",
    "id": "DFB80D1A07A5496194BA81030D54E45E",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 卷积层与全连接层的对比\n",
    "\n",
    "二维卷积层经常用于处理图像，与此前的全连接层相比，它主要有两个优势：\n",
    "\n",
    "一是全连接层把图像展平成一个向量，在输入图像上相邻的元素可能因为展平操作不再相邻，网络难以捕捉局部信息。而卷积层的设计，天然地具有提取局部信息的能力。\n",
    "\n",
    "二是卷积层的参数量更少。不考虑偏置的情况下，一个形状为$(c_i, c_o, h, w)$的卷积核的参数量是$c_i \\times c_o \\times h \\times w$，与输入图像的宽高无关。假如一个卷积层的输入和输出形状分别是$(c_1, h_1, w_1)$和$(c_2, h_2, w_2)$，如果要用全连接层进行连接，参数数量就是$c_1 \\times c_2 \\times h_1 \\times w_1 \\times h_2 \\times w_2$。使用卷积层可以以较少的参数数量来处理更大的图像。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_qhv3vji",
    "id": "3B6B64EC47384FD78A0CF2BD157ABDC5",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 卷积层的简洁实现\n",
    "\n",
    "我们使用Pytorch中的`nn.Conv2d`类来实现二维卷积层，主要关注以下几个构造函数参数：\n",
    "\n",
    "* `in_channels` (python:int) – Number of channels in the input imag\n",
    "* `out_channels` (python:int) – Number of channels produced by the convolution\n",
    "* `kernel_size` (python:int or tuple) – Size of the convolving kernel\n",
    "* `stride` (python:int or tuple, optional) – Stride of the convolution. Default: 1\n",
    "* `padding` (python:int or tuple, optional) – Zero-padding added to both sides of the input. Default: 0\n",
    "* `bias` (bool, optional) – If True, adds a learnable bias to the output. Default: True\n",
    "\n",
    "`forward`函数的参数为一个四维张量，形状为$(N, C_{in}, H_{in}, W_{in})$，返回值也是一个四维张量，形状为$(N, C_{out}, H_{out}, W_{out})$，其中$N$是批量大小，$C, H, W$分别表示通道数、高度、宽度。\n",
    "\n",
    "代码讲解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "graffitiCellId": "id_50vlm3f",
    "id": "8C48648624FC4CB98EB0FC69A020F59C",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([4, 2, 3, 5])\n",
      "Y.shape:  torch.Size([4, 3, 3, 5])\n",
      "weight.shape:  torch.Size([3, 2, 3, 5])\n",
      "bias.shape:  torch.Size([3])\n"
     ]
    }
   ],
   "source": [
    "X = torch.rand(4, 2, 3, 5)\n",
    "print(X.shape)\n",
    "\n",
    "conv2d = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=(3, 5), stride=1, padding=(1, 2))\n",
    "Y = conv2d(X)\n",
    "print('Y.shape: ', Y.shape)\n",
    "print('weight.shape: ', conv2d.weight.shape)\n",
    "print('bias.shape: ', conv2d.bias.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_h4crb33",
    "id": "C18215EE5FBC43F5867D1F384A2FC328",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 池化\n",
    "\n",
    "### 二维池化层\n",
    "\n",
    "池化层主要用于缓解卷积层对位置的过度敏感性。同卷积层一样，池化层每次对输入数据的一个固定形状窗口（又称池化窗口）中的元素计算输出，池化层直接计算池化窗口内元素的最大值或者平均值，该运算也分别叫做最大池化或平均池化。图6展示了池化窗口形状为$2\\times 2$的最大池化。\n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5nfob3odo.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "图6 池化窗口形状为 2 x 2 的最大池化\n",
    "\n",
    "二维平均池化的工作原理与二维最大池化类似，但将最大运算符替换成平均运算符。池化窗口形状为$p \\times q$的池化层称为$p \\times q$池化层，其中的池化运算叫作$p \\times q$池化。\n",
    "\n",
    "池化层也可以在输入的高和宽两侧填充并调整窗口的移动步幅来改变输出形状。池化层填充和步幅与卷积层填充和步幅的工作机制一样。\n",
    "\n",
    "在处理多通道输入数据时，池化层对每个输入通道分别池化，但不会像卷积层那样将各通道的结果按通道相加。这意味着池化层的输出通道数与输入通道数相等。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_xeq3hyv",
    "id": "9AB630787D9B4A93866C9A98A23A3C95",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 池化层的简洁实现\n",
    "\n",
    "我们使用Pytorch中的`nn.MaxPool2d`实现最大池化层，关注以下构造函数参数：\n",
    "\n",
    "* `kernel_size` – the size of the window to take a max over\n",
    "* `stride` – the stride of the window. Default value is kernel_size\n",
    "* `padding` – implicit zero padding to be added on both sides\n",
    "\n",
    "`forward`函数的参数为一个四维张量，形状为$(N, C, H_{in}, W_{in})$，返回值也是一个四维张量，形状为$(N, C, H_{out}, W_{out})$，其中$N$是批量大小，$C, H, W$分别表示通道数、高度、宽度。\n",
    "\n",
    "代码讲解"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "graffitiCellId": "id_euby6h0",
    "id": "055AED0960484D6F8B219367AC8542F5",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[[[ 0.,  1.,  2.,  3.],\n",
      "          [ 4.,  5.,  6.,  7.],\n",
      "          [ 8.,  9., 10., 11.],\n",
      "          [12., 13., 14., 15.]],\n",
      "\n",
      "         [[16., 17., 18., 19.],\n",
      "          [20., 21., 22., 23.],\n",
      "          [24., 25., 26., 27.],\n",
      "          [28., 29., 30., 31.]]]])\n",
      "tensor([[[[ 5.,  6.,  7.,  7.],\n",
      "          [13., 14., 15., 15.]],\n",
      "\n",
      "         [[21., 22., 23., 23.],\n",
      "          [29., 30., 31., 31.]]]])\n"
     ]
    }
   ],
   "source": [
    "X = torch.arange(32, dtype=torch.float32).view(1, 2, 4, 4)\n",
    "pool2d = nn.MaxPool2d(kernel_size=3, padding=1, stride=(2, 1))\n",
    "Y = pool2d(X)\n",
    "print(X)\n",
    "print(Y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_br4s548",
    "id": "E06C633237BF4157872396D0C262310B",
    "jupyter": {},
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "平均池化层使用的是`nn.AvgPool2d`，使用方法与`nn.MaxPool2d`相同。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
